<template>
  <!-- 面实体组件：通过传入多边形经纬高数组绘制填充面 -->
  <div style="display: none"></div>
</template>

<script setup>
import { inject, onMounted, onBeforeUnmount, watch, ref } from "vue";
import * as Cesium from "cesium";

const CESIUM_VIEWER_KEY = "cesiumViewer";
// 变量：注入的 viewer 引用（ref）
const viewerRef = inject(CESIUM_VIEWER_KEY, null);

// props：
// - positions：多边形顶点数组（[{lon,lat,height}]）
// - material：填充材质（CSS 色值）
// - outline：是否描边
// - outlineColor：描边颜色
// - heightReference：高度参考（none/clamp/relative）
// - show：是否显示
const props = defineProps({
  positions: { type: Array, required: true },
  material: { type: String, default: "rgba(0,229,255,0.4)" },
  outline: { type: Boolean, default: true },
  outlineColor: { type: String, default: "#00e5ff" },
  heightReference: { type: String, default: "none" },
  show: { type: Boolean, default: true },
});

// 变量：当前面实体引用
const entityRef = ref(null);

onMounted(() => {
  if (!viewerRef) return;
  const tryCreate = () => {
    if (!viewerRef.value) return false;
    createOrUpdate();
    return true;
  };
  if (!tryCreate()) {
    const stop = watch(() => viewerRef.value, (v) => {
      if (v) {
        createOrUpdate();
        stop();
      }
    });
  }
});

onBeforeUnmount(() => {
  const viewer = viewerRef && viewerRef.value;
  if (viewer && entityRef.value) viewer.entities.remove(entityRef.value);
  entityRef.value = null;
});

watch(() => ({ ...props }), () => createOrUpdate(), { deep: true });

// 方法：创建或更新面实体
function createOrUpdate() {
  const viewer = viewerRef && viewerRef.value;
  if (!viewer) return;
  const degrees = [];
  props.positions.forEach((p) => degrees.push(p.lon, p.lat, p.height ?? 0));
  const hierarchy = Cesium.Cartesian3.fromDegreesArrayHeights(degrees);
  const material = Cesium.Color.fromCssColorString(props.material);
  const outlineColor = Cesium.Color.fromCssColorString(props.outlineColor);

  const heightReference =
    props.heightReference === "clamp"
      ? Cesium.HeightReference.CLAMP_TO_GROUND
      : props.heightReference === "relative"
      ? Cesium.HeightReference.RELATIVE_TO_GROUND
      : Cesium.HeightReference.NONE;

  if (entityRef.value) {
    entityRef.value.polygon.hierarchy = new Cesium.ConstantProperty(hierarchy);
    entityRef.value.polygon.material = material;
    entityRef.value.polygon.heightReference = heightReference;
    entityRef.value.polygon.outline = props.outline;
    entityRef.value.polygon.outlineColor = outlineColor;
    entityRef.value.show = props.show;
  } else {
    entityRef.value = viewer.entities.add({
      show: props.show,
      polygon: {
        hierarchy,
        material,
        heightReference,
        outline: props.outline,
        outlineColor,
      },
    });
  }
}

defineExpose({ getEntity: () => entityRef.value });
</script>

<style scoped>
</style>


